package com.atzly.community.controller;

import com.atzly.community.constant.CommentConstant;
import com.atzly.community.entity.Event;
import com.atzly.community.event.EventProducter;
import com.atzly.community.utils.CommunityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成长图
 * 用户页面需要编写
 *
 * @author zlysimida
 * @date 2021/9/5 - 9:04
 */
@Controller
@Slf4j
public class ShareController implements CommentConstant {

    @Value("${community.path.domin}")
    private String domin;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.command}")
    private String command;

    @Value("${wk.image.storage}")
    private String storgeLocation;

    @Autowired
    private EventProducter producter;

    @GetMapping("/share")
    @ResponseBody
    public String wkImage(String htmlUrl) {
        // 文件名
        String filename = CommunityUtils.randomString();
        // 异步处理长图任务
        Event event = new Event()
                .setTopic(TOPIC_SHARE_IMAGE)
                .setData("filename", filename)
                .setData("htmlUrl", htmlUrl)
                .setData("suffix", "png");
        producter.sendMessage(event);

        // 返回访问路径 http:ip:port/community/share/image/filename
        Map<String, Object> map = new HashMap<>();
        map.put("shareUrl", domin + contextPath + "/share/image/" + filename);
        return CommunityUtils.JsontoString(0, null, map);
    }

    // 获取长图
    @GetMapping("/share/image/{filename}")
    public void getShareImage(@PathVariable("filename") String filename,
                              HttpServletResponse response) {
        // 从本地读取长图返回给用户
        response.setContentType("image/png");
        File file = new File(storgeLocation + "/" + filename + ".png");
        try (
                OutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(file);
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
            log.info("从本地读取图片成功!");
        } catch (IOException e) {
            log.error("从本地读取文件失败! err{}", e.getMessage());
        }
    }
}
